/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.rpc.excel;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.entity.QueryInfo;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.cache.dd.DicInfoCache;
import com.je.meta.rpc.dictionary.DictionaryRpcService;
import com.je.meta.service.ExcelService;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

import static com.google.common.base.Strings.isNullOrEmpty;

/**
 * @program: jecloud-meta
 * @author: LIULJ
 * @create: 2021/8/9
 * @description: Excel远程调用方法实现
 */
@RpcSchema(schemaId = "excelRpcService")
public class ExcelRpcServiceImpl implements ExcelRpcService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private DicInfoCache dicInfoCache;
    @Autowired
    private DictionaryRpcService dictionaryRpcService;
    @Autowired
    private ExcelService excelService;

    private static final String COLUMNS = "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE," +
            "RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO";

    /**
     * 可导出的字段
     * rownumberer 序号  0
     * uxcolumn 字段     1
     */
    private static List<String> EXPORT_TYPE = Lists.newArrayList("rownumberer", "uxcolumn");


    /**
     * 列表表单字段
     */
    private static final String COLUMNS_CONFIG_TABLE_CODE = "JE_CORE_VCOLUMNANDFIELD";

    @Override
    public List<List<Object>> buildExportData(String funcId, List<DynaBean> datas, Map<String, Map<String, String>> ddInfos, List<DynaBean> formColumns) {
        return excelService.buildExportData(funcId,datas,ddInfos,formColumns);
    }
    @Override
    public Map<String, Map<String, String>> buildDicDatas(List<DynaBean> columns) {
        Map<String, Map<String, String>> maps = new HashMap<String, Map<String, String>>();
        Set<String> ddCodes = new HashSet<String>();
        for (DynaBean column : columns) {
            String xtype = column.getStr("RESOURCEFIELD_XTYPE");
            if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield"}, xtype)) {
                String configInfo = column.getStr("RESOURCEFIELD_CONFIGINFO");
                if (StringUtil.isNotEmpty(configInfo)) {
                    ddCodes.add(configInfo.split(ArrayUtils.SPLIT)[0]);
                }
            }
        }
        if (ddCodes.size() > 0) {
            List<DynaBean> dictionarys = metaService.select("JE_CORE_DICTIONARY", ConditionsWrapper.builder().in("DICTIONARY_DDCODE", ddCodes).apply("and (SY_STATUS = '' or SY_STATUS = '1')"), "JE_CORE_DICTIONARY_ID,DICTIONARY_DDCODE");
            for (DynaBean dictionary : dictionarys) {
                List<DynaBean> items = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder().eq("DICTIONARYITEM_DICTIONARY_ID", dictionary.getStr("JE_CORE_DICTIONARY_ID")).eq("SY_FLAG", "1").ne("SY_NODETYPE", "ROOT"), "JE_CORE_DICTIONARYITEM_ID,DICTIONARYITEM_ITEMCODE,DICTIONARYITEM_ITEMNAME");
                Map<String, String> ddItems = new HashMap<String, String>();
                for (DynaBean item : items) {
                    if (StringUtil.isNotEmpty(item.getStr("DICTIONARYITEM_ITEMCODE"))) {
                        ddItems.put(item.getStr("DICTIONARYITEM_ITEMCODE"), item.getStr("DICTIONARYITEM_ITEMNAME"));
                    }
                }
                maps.put(dictionary.getStr("DICTIONARY_DDCODE"), ddItems);
            }
        }
        return maps;
    }

    @Override
    public List<DynaBean> getReportColumns(String funcId,String fieldPlan) {
        //DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId, "JE_CORE_FUNCINFO_ID,FUNCINFO_GRIDPRINTINFO");
        DynaBean printPlan = metaService.selectOne("JE_CORE_RESOURCECOLUMN_PRINT_PLAN",ConditionsWrapper.builder().eq("PLAN_FUNCINFO_ID",funcId).eq("PLAN_DEFAULT","1"));
        String gridPrintInfoStr = printPlan.getStr("PLAN_PRINT_CONFIG", "{}");
        List<String> columnCodes = new ArrayList<String>();
        JSONObject gridPrintInfo = JSONObject.parseObject(gridPrintInfoStr);
        JSONArray resColumns = gridPrintInfo.getJSONArray("relColumns");
        for (Integer i = 0; i < resColumns.size(); i++) {
            JSONObject columnObj = resColumns.getJSONObject(i);
            String columnCode = columnObj.getString("dataIndex");
            if (columnObj.getBoolean("hidden") == false) {
                columnCodes.add(columnCode);
                if (columnObj.containsKey("columns")) {
                    JSONArray arrays = columnObj.getJSONArray("columns");
                    for (Integer j = 0; j < arrays.size(); j++) {
                        JSONObject cObj = arrays.getJSONObject(j);
                        String cCode = cObj.getString("dataIndex");
                        if (cObj.getBoolean("hidden") == false) {
                            columnCodes.add(cCode);
                        }
                    }
                }
            }
        }
        List<DynaBean> columns = new ArrayList<DynaBean>();
        List<DynaBean> queryColumns = metaService.select("JE_CORE_VCOLUMNANDFIELD", ConditionsWrapper.builder().apply(" AND RESOURCEFIELD_PLAN_ID='"+fieldPlan+"'  AND ( RESOURCEFIELD_XTYPE NOT IN ( 'ckeditor', 'uxfilefield', 'uxfilesfield' ) OR RESOURCECOLUMN_XTYPE = 'rownumberer') AND RESOURCECOLUMN_FUNCINFO_ID='" + funcId + "' AND RESOURCECOLUMN_CODE IN (" + StringUtil.buildArrayToString(ArrayUtils.getArray(columnCodes)) + ") AND RESOURCECOLUMN_XTYPE NOT IN ('actioncolumn')"), "RESOURCECOLUMN_MORECOLUMNNAME,RESOURCECOLUMN_WIDTH,RESOURCECOLUMN_CODE,RESOURCECOLUMN_XTYPE,RESOURCECOLUMN_NAME,RESOURCEFIELD_XTYPE,RESOURCEFIELD_CONFIGINFO");
        for (Integer i = 0; i < resColumns.size(); i++) {
            JSONObject columnObj = resColumns.getJSONObject(i);
            String columnCode = columnObj.getString("dataIndex");
            if (columnObj.getBoolean("hidden") == false) {
                for (DynaBean column : queryColumns) {
                    if (columnCode.equals(column.getStr("RESOURCECOLUMN_CODE"))) {
                        column.set("RESOURCECOLUMN_MORECOLUMNNAME", columnObj.getString("moreColumnName"));
                        if (columnObj.containsKey("width")) {
                            column.set("RESOURCECOLUMN_WIDTH", columnObj.getString("width"));
                        }
                        if (columnObj.containsKey("columns")) {
                            JSONArray arrays = columnObj.getJSONArray("columns");
                            for (Integer j = 0; j < arrays.size(); j++) {
                                JSONObject cObj = arrays.getJSONObject(j);
                                String cCode = cObj.getString("dataIndex");
                                if (cObj.getBoolean("hidden") == false) {
                                    for (DynaBean c : queryColumns) {
                                        if (cCode.equals(c.getStr("RESOURCECOLUMN_CODE"))) {
                                            c.set("RESOURCECOLUMN_MORECOLUMNNAME", cObj.getString("moreColumnName"));
                                            if (cObj.containsKey("width")) {
                                                c.set("RESOURCECOLUMN_WIDTH", cObj.getString("width"));
                                            }
                                            columns.add(c);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        columns.add(column);
                        break;
                    }
                }
            }
        }
        return columns;
    }

    @Override
    public List<List<String>> getReportTile(String funcId,String title) {
        List<List<String>> headTitles = Lists.newArrayList();
        if(StringUtil.isEmpty(title)){
            title = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId, "FUNCINFO_FUNCNAME").getStr("FUNCINFO_FUNCNAME");
        }
        List<DynaBean> columnDynaBeans = metaService.select("JE_CORE_RESOURCECOLUMN", ConditionsWrapper.builder().eq("RESOURCECOLUMN_FUNCINFO_ID", funcId)
                .eq("RESOURCECOLUMN_HIDDEN", "0").orderByAsc("SY_ORDERINDEX"), COLUMNS);
        for (DynaBean column : columnDynaBeans) {
            String type = column.getStr("RESOURCECOLUMN_XTYPE");
            String groupCode = column.getStr("RESOURCECOLUMN_MORECOLUMNNAME");
            if (EXPORT_TYPE.contains(type) && isNullOrEmpty(groupCode)) {
                headTitles.add(Lists.newArrayList(title, column.getStr("RESOURCECOLUMN_NAME")));
            }
            if (!EXPORT_TYPE.contains(type) || isNullOrEmpty(groupCode)) {
                continue;
            }
            List<String> head = new ArrayList<>();
            head.add(title);
            head.addAll(getChildColumns(column, new ArrayList<>(), columnDynaBeans));
            Collections.reverse(head);
            headTitles.add(head);
        }
        return headTitles;
    }

    private List<String> getChildColumns(DynaBean excelTableColumn, List<String> heads, List<DynaBean> columnDynaBeans) {
        heads.add(excelTableColumn.getStr("RESOURCECOLUMN_NAME"));
        if (isNullOrEmpty(excelTableColumn.getStr("RESOURCECOLUMN_MORECOLUMNNAME"))) {
            return heads;
        }
        for (DynaBean columnBean : columnDynaBeans) {
            if (excelTableColumn.getStr("RESOURCECOLUMN_MORECOLUMNNAME").equals(columnBean.getStr("RESOURCECOLUMN_CODE"))) {
                getChildColumns(columnBean, heads, columnDynaBeans);
            }
        }
        return heads;
    }


    @Override
    public JSONObject preparePreviewData(String code, String temIds) {
        JSONObject resultObj = new JSONObject();
        DynaBean group = metaService.selectOne("JE_CORE_EXCELGROUP", ConditionsWrapper.builder().eq("GROUPCODE", code));
        //系统处理方式
        List<DynaBean> temConfigs = metaService.select("JE_EXCEL_CONFIGTEMP", ConditionsWrapper.builder().in("JE_EXCEL_CONFIGTEMP_ID", Splitter.on(",").splitToList(temIds)));
        Map<String, List<DynaBean>> results = new HashMap<String, List<DynaBean>>();
        List<DynaBean> sheets = new ArrayList<DynaBean>();
        Map<String, Map<String, DynaBean>> allFieldInfos = new HashMap<String, Map<String, DynaBean>>();
        for (DynaBean temConfig : temConfigs) {
            String fieldConfigStrs = temConfig.getStr("CONFIGTEMP_FIELDCONFIG");
            List<DynaBean> lists = new ArrayList<DynaBean>();
//			Map<String,String> fieldConfigs=new HashMap<String,String>();
//			for(String fieldConfig:fieldConfigStrs.split(",")){
//				fieldConfigs.put(fieldConfig.split("~")[0], fieldConfig.split("~")[1]);
//			}
            DynaBean sheet = metaService.selectOneByPk("JE_CORE_EXCELSHEET", temConfig.getStr("JE_CORE_EXCELSHEET_ID"));
            List<DynaBean> fields = metaService.select("JE_CORE_EXCELFIELD", ConditionsWrapper.builder().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")).orderByAsc("SY_ORDERINDEX"));
            Map<String, DynaBean> fieldInfos = new HashMap<String, DynaBean>();
            Map<String, DynaBean> fieldCodeInfos = new HashMap<String, DynaBean>();
            for (DynaBean field : fields) {
                String columnName = field.getStr("EXCELFIELD_COLUMN");
                //处理默认值
                if (StringUtil.isNotEmpty(columnName)) {
                    fieldInfos.put(columnName, field);
                }
            }
            List<DynaBean> datas = metaService.select("JE_EXCEL_DATATEMP", ConditionsWrapper.builder()
                    .eq("JE_EXCEL_CONFIGTEMP_ID", temConfig.getStr("JE_EXCEL_CONFIGTEMP_ID"))
                    .in("CODE", Lists.newArrayList("-1", "1"))
                    .orderByAsc("SY_ORDERINDEX"));
            for (DynaBean data : datas) {
                DynaBean dynaBean = new DynaBean(sheet.getStr("TABLECODE", ""), true);
                for (String fieldConfig : fieldConfigStrs.split(",")) {
                    String thisField = fieldConfig.split("~")[0];
                    String targerField = fieldConfig.split("~")[1];
                    dynaBean.set(targerField, data.get(thisField));
                }
                lists.add(dynaBean);
            }
            sheet.set("SHEETNAME", temConfig.getStr("CONFIGTEMP_SHEETNAME"));
            int sheetOrder = sheet.getInt("SY_ORDERINDEX", 0) - 1;
            String key = "sheet" + sheetOrder;
            results.put(key, lists);
            sheets.add(sheet);
            allFieldInfos.put(key, fieldCodeInfos);
        }

        resultObj.put("results", results);
        resultObj.put("sheets", sheets);
        resultObj.put("allFieldInfos", allFieldInfos);
        resultObj.put("group", group);
        return resultObj;
    }

    @Override
    public void afterPreviewData(String excelGroupId) {
        metaService.executeSql(" DELETE FROM JE_EXCEL_GROUPTEM WHERE JE_CORE_EXCELGROUP_ID='" + excelGroupId + "'");
    }

    @Override
    public List<Map<String, Object>> funcTemplateListById(String sheetId) {
        return excelService.funcTemplateListById(sheetId);
    }

    @Override
    public List<Map<String, Object>> funcTemplateList(String funcId) {
        //查询功能对应的模板
        List<Map<String, Object>> list = metaService.selectSql(String.format("select t.JE_CORE_EXCELSHEET_ID,t.JE_CORE_EXCELGROUP_ID,n.GROUPNAME,n.EXCELGROUP_FILE from JE_CORE_EXCELSHEET t INNER JOIN JE_CORE_EXCELGROUP n on n.JE_CORE_EXCELGROUP_ID = t.JE_CORE_EXCELGROUP_ID and n.EXCELGROUP_FILE is not null and n.EXCELGROUP_FILE != '' where t.FUNCID = '%s'", funcId));
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> funcTemplateListWithComustomer(String funcId, String comustomer) {
        //查询功能对应的模板
        List<Map<String, Object>> newList = new ArrayList<>();
        //人大金仓!=''查询不出数据
        String sql = "select t.JE_CORE_EXCELSHEET_ID,t.JE_CORE_EXCELGROUP_ID,n.GROUPNAME,n.EXCELGROUP_FILE from JE_CORE_EXCELSHEET t INNER JOIN JE_CORE_EXCELGROUP n on n.JE_CORE_EXCELGROUP_ID = t.JE_CORE_EXCELGROUP_ID where t.FUNCID = {0}";
        List<Map<String, Object>> list = metaService.selectSql(sql, funcId);
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        for (Map<String, Object> map : list) {
            if (!Objects.isNull(map.get("EXCELGROUP_FILE"))) {
                if (!isNullOrEmpty(String.valueOf(map.get("EXCELGROUP_FILE")))) {
                    newList.add(map);
                }
            }
        }
        return newList;
    }

    @Override
    public JSONObject buildSheetInfoWithSheet(String previewTemId, String sheetName, Integer sheetOrder, List<DynaBean> fields, List<String> fieldConfigs) {
        JSONObject returnObj = new JSONObject();
        returnObj.put("sheetName", sheetName);
        returnObj.put("sheetIndex", sheetOrder);
        returnObj.put("temId", previewTemId);
        Map<String, String> fieldDbInfos = new HashMap<String, String>();
        for (String fc : fieldConfigs) {
            String fieldCode = fc.split("~")[1];
            String targerCode = fc.split("~")[0];
            fieldDbInfos.put(fieldCode, targerCode);
        }
        JSONArray columns = new JSONArray();
        for (DynaBean fieldInfo : fields) {
            JSONObject column = new JSONObject();
            JSONObject field = new JSONObject();
            if ("rownumberer".equals(fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                continue;
            }
            column.put("dataIndex", fieldDbInfos.get(fieldInfo.get("EXCELFIELD_CODE")));
            column.put("hidden", "1".equals(fieldInfo.get("EXCELFIELD_HIDDEN")));
            column.put("text", fieldInfo.getStr("EXCELFIELD_NAME"));
            column.put("width", fieldInfo.getInt("EXCELFIELD_WIDTH", 80));
            field.put("name", fieldDbInfos.get(fieldInfo.get("EXCELFIELD_CODE")));
            field.put("xtype", fieldInfo.getStr("EXCELFIELD_XTYPE"));
            String configInfo = fieldInfo.getStr("EXCELFIELD_CONFIGINFO", "");
            if (StringUtil.isNotEmpty(configInfo)) {
                if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield", "treessfield", "treessareafield", "gridssfield", "gridssareafield", "searchfield", "queryuserfield", "queryuserareafield"}, fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                    String[] confArray = configInfo.split(ArrayUtils.SPLIT);
                    if (confArray.length > 1) {
                        String thisFields = confArray[1];
                        String[] thisFieldArray = thisFields.split("~");
                        for (int i = 0; i < thisFieldArray.length; i++) {
                            thisFieldArray[i] = StringUtil.getDefaultValue(fieldDbInfos.get(thisFieldArray), thisFieldArray[i]);
                        }
                        confArray[1] = StringUtil.buildSplitString(thisFieldArray, "~");
                        configInfo = StringUtil.buildSplitString(confArray, ",");
                    }
                }
            }
            field.put("configInfo", configInfo);
            field.put("value", fieldInfo.getStr("EXCELFIELD_VALUE"));
            column.put("field", field);
            columns.add(column);
        }
        returnObj.put("columns", columns);
        return returnObj;
    }

    @Override
    public JSONArray buildSheetInfo(String groupId, String groupTemId) {
        List<DynaBean> sheets = metaService.select("JE_CORE_EXCELSHEET", ConditionsWrapper.builder().eq("JE_CORE_EXCELGROUP_ID", groupId));
        List<DynaBean> configTems = metaService.select("JE_EXCEL_CONFIGTEMP", ConditionsWrapper.builder().eq("JE_EXCEL_GROUPTEM_ID", groupTemId));
        JSONArray arrays = new JSONArray();
        for (DynaBean sheet : sheets) {
            Integer sheetOrder = sheet.getInt("SY_ORDERINDEX", 1) - 1;
            JSONObject sheetObj = new JSONObject();
            List<DynaBean> fields = metaService.select("JE_CORE_EXCELFIELD", ConditionsWrapper.builder().eq("JE_CORE_EXCELSHEET_ID", sheet.getStr("JE_CORE_EXCELSHEET_ID")).orderByAsc("SY_ORDERINDEX"));
            sheetObj.put("sheetName", "sheet" + sheetOrder);
            sheetObj.put("sheetIndex", sheetOrder);
            String temId = "";
            String sheetName = "";
            for (DynaBean configTem : configTems) {
                if (configTem.getStr("JE_CORE_EXCELSHEET_ID", "").equals(sheet.getStr("JE_CORE_EXCELSHEET_ID"))) {
                    temId = configTem.getStr("JE_EXCEL_CONFIGTEMP_ID");
                    sheetName = configTem.getStr("CONFIGTEMP_SHEETNAME");
                    break;
                }
            }
            sheetObj.put("temId", temId);
            sheetObj.put("sheetName", sheetName);
            List<String> fieldConfigs = new ArrayList<String>();
            for (int i = 0; i < fields.size(); i++) {
                DynaBean field = fields.get(i);
                fieldConfigs.add("DATATEMP_FIELD" + (i + 1) + "~" + field.getStr("EXCELFIELD_CODE"));
            }
            Map<String, String> fieldDbInfos = new HashMap<String, String>();
            for (String fc : fieldConfigs) {
                String fieldCode = fc.split("~")[1];
                String targerCode = fc.split("~")[0];
                fieldDbInfos.put(fieldCode, targerCode);
            }
            JSONArray columns = new JSONArray();
            for (DynaBean fieldInfo : fields) {
                JSONObject column = new JSONObject();
                JSONObject field = new JSONObject();
                if ("rownumberer".equals(fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                    continue;
                }
                column.put("dataIndex", fieldDbInfos.get(fieldInfo.get("EXCELFIELD_CODE")));
                column.put("hidden", "1".equals(fieldInfo.get("EXCELFIELD_HIDDEN")));
                column.put("text", fieldInfo.getStr("EXCELFIELD_NAME"));
                column.put("width", fieldInfo.getInt("EXCELFIELD_WIDTH", 80));
                field.put("name", fieldDbInfos.get(fieldInfo.get("EXCELFIELD_CODE")));
                field.put("xtype", fieldInfo.getStr("EXCELFIELD_XTYPE"));
                String configInfo = fieldInfo.getStr("EXCELFIELD_CONFIGINFO", "");
                if (StringUtil.isNotEmpty(configInfo)) {
                    if (ArrayUtils.contains(new String[]{"rgroup", "cgroup", "cbbfield", "treessfield", "treessareafield", "gridssfield", "gridssareafield", "searchfield", "queryuserfield", "queryuserareafield"}, fieldInfo.getStr("EXCELFIELD_XTYPE"))) {
                        String[] confArray = configInfo.split(ArrayUtils.SPLIT);
                        if (confArray.length > 1) {
                            String thisFields = confArray[1];
                            String[] thisFieldArray = thisFields.split("~");
                            for (int i = 0; i < thisFieldArray.length; i++) {
                                thisFieldArray[i] = StringUtil.getDefaultValue(fieldDbInfos.get(thisFieldArray), thisFieldArray[i]);
                            }
                            confArray[1] = StringUtil.buildSplitString(thisFieldArray, "~");
                            configInfo = StringUtil.buildSplitString(confArray, ",");
                        }
                    }
                }
                field.put("configInfo", configInfo);
                field.put("value", fieldInfo.getStr("EXCELFIELD_VALUE"));
                column.put("field", field);
                columns.add(column);
            }
            sheetObj.put("columns", columns);
            arrays.add(sheetObj);
//			returnObj.put("temId", previewTemId);
        }
        return arrays;
    }

    @Override
    public void parseAllDzValues(DynaBean field, Map<String, Object> paramValues, Map<String, List<DynaBean>> dzValues, List<String> dzFields, Map<String, String> requestParams) {
        //选择其他表数据
        //字典设定
        String[] ddXtypes = new String[]{"cbbfield", "treessfield", "treessareafield", "cgroup", "rgroup"};
        String[] tableXtypes = new String[]{"gridssfield", "gridssareafield", "searchfield"};
        if ("1".equals(field.getStr("EXCELFIELD_CLDZ")) && StringUtil.isNotEmpty(field.getStr("EXCELFIELD_DBZDPZ"))) {
            //拉取结果集  根据字段类型拉取所有数据集  字段也要返回dynaBean  text code id
            String dzclType = field.getStr("EXCELFIELD_SJCL");
            if (!"ONE".equals(dzclType)) {
                String xtype = field.getStr("EXCELFIELD_XTYPE");
                if (ArrayUtils.contains(tableXtypes, xtype)) {
                    String dzTableCode = field.getStr("EXCELFIELD_TABLECODE");
                    String dzQuerySql = field.getStr("EXCELFIELD_QUERYSQL");
                    if (StringUtil.isNotEmpty(dzQuerySql)) {
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, paramValues);
                    }
                    List<DynaBean> dzLists = metaService.select(dzTableCode, ConditionsWrapper.builder().apply(dzQuerySql));
                    dzValues.put(field.getStr("EXCELFIELD_CODE"), dzLists);
                    //获取字典项
                } else if (ArrayUtils.contains(ddXtypes, xtype)) {
                    String configInfo = field.getStr("EXCELFIELD_CONFIGINFO");
                    List<DynaBean> lists = new ArrayList<DynaBean>();
                    if (StringUtil.isNotEmpty(configInfo)) {
                        String ddCode = configInfo.split(ArrayUtils.SPLIT)[0];
                        List<JSONTreeNode> dzLists = dictionaryRpcService.getAllTyepDdListItems(ddCode, requestParams, new QueryInfo(), false);
                        for (JSONTreeNode dzItem : dzLists) {
                            DynaBean bean = new DynaBean();
                            bean.set("text", dzItem.getText());
                            bean.set("code", dzItem.getCode());
                            bean.set("id", dzItem.getId());
                            bean.set("bean", dzItem.getBean());
                            lists.add(bean);
                        }
                    }
                    dzValues.put(field.getStr("EXCELFIELD_CODE"), lists);
                }
            }
            if(dzFields!=null){
                dzFields.add(field.getStr("EXCELFIELD_CODE"));
            }
        }
    }

    @Override
    public void doSetBeanDzValue(DynaBean fieldInfo, DynaBean dynaBean, Map<String, List<DynaBean>> dzValues, Map<String, Object> paramValues) {
        String dzclType = fieldInfo.getStr("EXCELFIELD_SJCL");
        String fieldCode = fieldInfo.getStr("EXCELFIELD_CODE");
        String configInfo = fieldInfo.getStr("EXCELFIELD_CONFIGINFO");
        String dbConfigInfo = fieldInfo.getStr("EXCELFIELD_DBZDPZ");
        String[] thisFields = configInfo.split(ArrayUtils.SPLIT)[1].split("~");
        String[] targFields = configInfo.split(ArrayUtils.SPLIT)[2].split("~");
        String value = dynaBean.getStr(fieldCode);
        String xtype = fieldInfo.getStr("EXCELFIELD_XTYPE");
        String[] ddXtypes = new String[]{"cbbfield", "treessfield", "treessareafield", "cgroup", "rgroup"};
        String[] tableXtypes = new String[]{"gridssfield", "gridssareafield", "searchfield", "queryuserfield", "queryuserareafield"};
        if (StringUtil.isNotEmpty(value) && StringUtil.isNotEmpty(configInfo) && StringUtil.isNotEmpty(dbConfigInfo)) {
            if (!"ONE".equals(dzclType)) {
                List<DynaBean> lists = dzValues.get(fieldCode);
                for (DynaBean data : lists) {
                    // EDIT BY ZHANGYD 20201111 FOR 查询选择无法正常带值
                    Boolean flag = false;
                    for (String dbInfo : dbConfigInfo.split(",")) {
                        if (!flag) {
                            String thisField = dbInfo.split("~")[0];
                            String targField = dbInfo.split("~")[1];
                            if (StringUtil.isNotEmpty(dynaBean.getStr(thisField)) && data.getStr(targField, "").equals(dynaBean.getStr(thisField))) {
                                flag = true;
                            }
                        }
                    }
                    // EDIT BY ZHANGYD 20201111 FOR 查询选择无法正常带值 end
                    //找到了数据
                    if (flag) {
                        for (int i = 0; i < targFields.length; i++) {
                            String targerField = targFields[i];
                            if (thisFields.length > i) {
                                String thisField = thisFields[i];
                                dynaBean.set(thisField, data.get(targerField));
                            }
                        }
                    }
                }
            } else {
                if (ArrayUtils.contains(tableXtypes, xtype)) {
                    String dzTableCode = fieldInfo.getStr("EXCELFIELD_TABLECODE");
                    String dzQuerySql = fieldInfo.getStr("EXCELFIELD_QUERYSQL");
                    Map<String, Object> beanSet = dynaBean.clone().getValues();
                    if (StringUtil.isNotEmpty(dzQuerySql)) {
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, paramValues);
                        dzQuerySql = StringUtil.parseKeyWord(dzQuerySql, beanSet);
                    }
                    List<String> sqlWheres = new ArrayList<String>();
                    for (String dbInfo : dbConfigInfo.split(",")) {
                        String thisField = dbInfo.split("~")[0];
                        String targField = dbInfo.split("~")[1];
                        sqlWheres.add(" " + targField + "='" + dynaBean.getStr(thisField) + "'");
                    }
                    List<DynaBean> dzLists = metaService.select(dzTableCode, ConditionsWrapper.builder().apply(dzQuerySql + " AND (" + StringUtil.buildSplitString(ArrayUtils.getArray(sqlWheres), " AND ") + ")"));
                    if (dzLists.size() > 0) {
                        DynaBean data = dzLists.get(0);
                        for (int i = 0; i < targFields.length; i++) {
                            String targerField = targFields[i];
                            if (thisFields.length > i) {
                                String thisField = thisFields[i];
                                dynaBean.set(thisField, data.get(targerField));
                            }
                        }
                    }
                } else if (ArrayUtils.contains(ddXtypes, xtype)) {
                    String ddCode = configInfo.split(ArrayUtils.SPLIT)[0];
                    DynaBean dictionary = dicInfoCache.getCacheValue(ddCode);
                    if (dictionary == null) {
                        dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode).apply("and (SY_STATUS = '' or SY_STATUS = '1')"));
                    }
                    String ddType = "";
                    if(dictionary != null) {
                        ddType = dictionary.getStr("DICTIONARY_DDTYPE");
                    }
                    Map<String, String> ddFields = new HashMap<String, String>();
                    ddFields.put("text", "DICTIONARYITEM_ITEMNAME");
                    ddFields.put("code", "DICTIONARYITEM_ITEMCODE");
                    ddFields.put("id", "JE_CORE_DICTIONARYITEM_ID");
                    List<String> sqlWheres = new ArrayList<String>();
                    for (String dbInfo : dbConfigInfo.split(",")) {
                        String thisField = dbInfo.split("~")[0];
                        String targField = dbInfo.split("~")[1];
                        sqlWheres.add(" " + ddFields.get(targField) + "='" + dynaBean.getStr(thisField) + "'");
                    }
                    if (DDType.LIST.equalsIgnoreCase(ddType) || DDType.TREE.equalsIgnoreCase(ddType)) {
                        List<DynaBean> dzLists = metaService.select("JE_CORE_DICTIONARYITEM", ConditionsWrapper.builder().apply(" AND DICTIONARYITEM_DICTIONARY_ID='" + dictionary.getStr("JE_CORE_DICTIONARY_ID") + "' AND (" + StringUtil.buildSplitString(ArrayUtils.getArray(sqlWheres), " AND ") + ")"));
                        if (dzLists.size() > 0) {
                            DynaBean data = dzLists.get(0);
                            for (int i = 0; i < targFields.length; i++) {
                                String targerField = targFields[i];
                                if (thisFields.length > i) {
                                    String thisField = thisFields[i];
                                    dynaBean.set(thisField, data.get(ddFields.get(targerField)));
                                }
                            }
                        }
                    }

                }
            }
        }
    }
}
